package com.hf.www.base.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import com.hf.www.base.common.Pager;
import com.hf.www.core.kit.SqlXmlKit;
import com.hf.www.core.plugin.annotation.Table;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * CREATE TABLE `sys_menus` (
 * `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '菜单编号',
 * `menuName` varchar(30) NOT NULL COMMENT '菜单名称',
 * `remark` varchar(30) DEFAULT NULL COMMENT '备注',
 * `isParent` tinyint(1) NOT NULL COMMENT '是否为父节点',
 * `parentID` int(11) NOT NULL COMMENT '父节点编号',
 * `url` varchar(200) DEFAULT NULL COMMENT 'URL',
 * `status` int(11) NOT NULL COMMENT '状态',
 * `sort` int(11) DEFAULT NULL COMMENT '排序',
 * PRIMARY KEY (`id`)
 * ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
 */
@SuppressWarnings("serial")
@Table(tableName = "sys_menus")
public class SysMenusModel extends Model<SysMenusModel> {

	public static final SysMenusModel dao = new SysMenusModel();
    Map<String, List<Record>> cMaps = new HashMap<String, List<Record>>(); 
	
	
	public List<SysMenusModel> allMenus() {
		return dao.find("SELECT IF(a.remark, CONCAT(a.menuName,'[',a.remark,']'), a.menuName) AS showName, a.* FROM sys_menus a ORDER BY sort ASC");
	}

	public List<Record> getLeftMenus(Integer uid){
		List<Record> list =  Db.find(SqlXmlKit.getSql("SysMenus.LeftMenus"),uid);
		Stack<Record> stack = new Stack<Record>();
		List<Record> parents = new ArrayList<Record>();
		for (Record record : list) {
			if(record.getBoolean("isParent")){
				stack.push(record);
				parents.add(record);
			}else{
				Record parent = null;
				while(parent==null && !stack.isEmpty()){
					Record temp = stack.peek();
					if(record.get("parentID").equals(temp.get("id"))){
						parent = temp;
					}else{
						stack.pop();
					}
				}
				if(parent != null){
					List<Record> childrens =  parent.get("childrens");
					if(childrens == null){
						childrens = new ArrayList<Record>();
						parent.set("childrens", childrens);
					}
					childrens.add(record);
				}else{
					System.out.println("no parents found!"+record);
				}
			}
		}
		return parents;
	}
	
	
	public Page<?> getAllMenus(Pager pager){
		
		return dao.paginate(pager.getPageNo(), pager.getPageSize(), "select * ", " from sys_menus where type=? " , pager.getParam("type"));
	}
	
	/**
	 * 批量删除菜单
	 * @param ids
	 */
	@Before(Tx.class)
	public void batchDel(String ids){
		if(StrKit.isBlank(ids)) 
			return ;
		String []arrs = ids.split(",");
		for (String id : arrs) {
			Db.update(" delete from sys_role_menu where menuID in(?)", id);
			if("".equalsIgnoreCase(id.trim())) 
				continue;
			dao.deleteById(id);
		}
	}
	
	
	/**
	 * 
	 * 编辑保存
	 * 
	 * @param menu
	 * @return
	 */
	public boolean editSave(SysMenusModel menu){
		boolean result = false;
		
		if(StrKit.notNull(menu.get("id")) && !"".equals(menu.get("id"))){
			result = menu.update();
		}else{
			result = menu.save();
		}
		return result ;
	}
	
	
	
	
	
	/**
	 * 获取制定类型的菜单
	 * @param type
	 * @return
	 */
	@Before(Tx.class)
	public List<Record> getMenus(Integer type){
		
		List<Record>  rlist = null ,
				      clist = null ,
					  list = null ;
		
		list = Db.find(" select * from sys_menus where type=? and parentID not in(select id from sys_menus ) order by ifnull(sort,0) asc " , type);
		rlist = new ArrayList<Record>();
		for (Record rec : list) { 
			
			clist = getChildrensMenus(type , rec.getInt("id"));
			if(clist != null && clist.size() > 0){
				rec.set("childrens", clist);
			}
			
			rlist.add(rec);
		} 
		
		return rlist ;
	}
	
	
	
	/**
	 * 获取指定类型下的某菜单的所有子菜单
	 * @param type
	 * @param menuId
	 * @return
	 */
	public List<Record> getChildrensMenus(Integer type , Integer menuId ){ 
         
		List<Record> rlist = new ArrayList<Record>(),  
		 		  clist = null ,
				  list = null ;
	
		list = Db.find(" select * from sys_menus where  type=? and parentID=? order by ifnull(sort,0) asc " ,type, menuId );
		for (Record rec : list) {
			clist = getChildrensMenus(type , rec.getInt("id"));
			if(clist != null && clist.size() > 0){
				rec.set("childrens", clist);
			}
			
			rlist.add(rec); 
		} 
		return rlist ;
		
	}
	
	
	public List<SysMenusModel> getPMenus(Map<String, Object> params){
		
		return dao.find(" select * from sys_menus where isParent=? and type=? ", params.get("isParent") , params.get("type") ) ;
	} 
}
